package org.lxy.controller;

import org.lxy.config.UserInfoConfig;
import org.lxy.core.exception.BusException;
import org.lxy.domain.UserInfoEntity;
import org.lxy.domain.constant.CoreConstant;
import org.lxy.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 卢心怡
 */
public class BaseController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserInfoService userInfoService;

    public UserInfoEntity getUserInfo(){
        return getUserInfo(false);
    }


    public UserInfoEntity getUserInfo(boolean isLogin){
        if (Objects.nonNull(request.getCookies()) && request.getCookies().length>0){
            Cookie cookie = Arrays.asList(request.getCookies()).stream().filter(e -> CoreConstant.USER_COOKIE.equals(e.getName())).findFirst().orElse(null);
            if (Objects.nonNull(cookie)){
                UserInfoEntity userInfoEntity = UserInfoConfig.GLOBAL_USER_INFO.get(cookie.getValue());
                if (Objects.nonNull(userInfoEntity)){
                    return userInfoService.getById(userInfoEntity.getId());
                }
            }
            if (isLogin){
                return null;
            }
        }
        //throw new BusException("请先登录!",CoreConstant.LOGIN_HTML);
        return null;
    }

}
